import {
  reqGetDoctors,
  reqGetHospitalDepartment,
  reqGetHospitalSchedule,
} from "@/api/hospital/hospitalList";
import {
  ReqGetDepartmentsResponse,
  ReqGetDoctorsResponse,
  ScheduleRuleItem,
} from "@/api/hospital/model/hospitalListType";
import { Button, Card, Col, Pagination, Row, Tag } from "antd";
import Table, { ColumnsType } from "antd/lib/table";
import Tree, { DataNode } from "antd/lib/tree";
import React, { Key, useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";

export default function HospitalSchedule() {
  //声明表格的结构
  const columns: ColumnsType<any> = [
    {
      title: "序号",
      render: (value, row, index) => {
        return index + 1;
      },
    },
    {
      title: "职称",
      dataIndex: "title",
    },
    {
      title: "号源时间",
      dataIndex: "workDate",
    },
    {
      title: "总预约数",
      dataIndex: "reservedNumber",
    },
    {
      title: "剩余预约数",
      dataIndex: "availableNumber",
    },
    {
      title: "挂号费",
      dataIndex: "amount",
    },
    {
      title: "擅长技能",
      dataIndex: "skill",
    },
  ];

  //计算左侧 div 的高度
  let height =
    document.documentElement.clientHeight - 64 - 34 - 24 * 2 - 22 - 14 - 10;

  //获取医院的编号
  let hoscode = useParams().id;
  //与分页相关的几个状态
  let [current, setCurrent] = useState<number>(1);
  let [total, setTotal] = useState<number>(20);
  let [pageSize, setPageSize] = useState<number>(5);
  //声明状态管理医院科室信息
  let [departments, setDepartments] = useState<ReqGetDepartmentsResponse>([]);
  //声明状态管理展开科室的 key
  let [expandedKeys, setExpandedKeys] = useState<string[]>([]);
  //声明状态管理选中的科室
  let [depcode, setDepcode] = useState<string>("");
  //声明状态管理排班规则
  let [schedule, setSchedule] = useState<ScheduleRuleItem[]>([]);
  //声明状态管理出诊医生列表
  let [doctors, setDoctors] = useState<ReqGetDoctorsResponse>([]);
  //医院名称的状态
  let [hosname, setHosname] = useState<string>("");
  //科室名称的状态
  let [depname, setDepname] = useState<string>("");
  //挂号日期的状态
  let [workDate, setWorkDate] = useState<string>("");
  let navigate = useNavigate();

  //声明函数
  let getDepartments = async () => {
    //发送请求获取所有的科室
    let result = await reqGetHospitalDepartment(hoscode as string);
    //使一级的科室禁用 [{children:[], disabled: true}, {children: []}, {}]
    let resDis = result.map((item) => {
      let obj = { ...item, disabled: true };
      return obj;
    });
    //使一级科室都展开
    let keys = result.map((item) => item.depcode);
    //更新展开科室的 key
    setExpandedKeys(keys);
    //更新科室的状态
    setDepartments(resDis);
    //获取选中的科室的 key
    let depcode = result[0].children ? result[0].children[0].depcode : "";
    let depname = result[0].children ? result[0].children[0].depname : "";

    //更新选中 key 的状态
    setDepcode(depcode);
    setDepname(depname);
  };

  //组件挂载完成的回调
  useEffect(() => {
    getDepartments();
  }, []);

  //科室编号更新后的回调
  useEffect(() => {
    if (depcode) {
      getSchedules();
    }
  }, [depcode, depname, current]);

  //挂号事件更新后的回调
  useEffect(() => {
    if(workDate){
      getDoctors();
    }
  }, [workDate]);

  //获取排班规则
  let getSchedules = async () => {
    try {
      //发送请求获取医院排班规则
      let res = await reqGetHospitalSchedule({
        page: current,
        limit: pageSize,
        hoscode: hoscode as string,
        depcode: depcode,
      });

      //设置科室编号的状态
      setHosname(res.baseMap.hosname);
      //设置分页总数状态
      setTotal(res.total);
      //设置排班规则的状态
      setSchedule(res.bookingScheduleList);
      //获取 workDate 的值
      let workDate = res.bookingScheduleList[0].workDate;
      setWorkDate(workDate);
      
    } catch (e) {
      setSchedule([]);
      setDoctors([]);
    }
  };

  //获取医生列表
  let getDoctors = async () => {
    //获取医生列表
    let doctors = await reqGetDoctors({
      hoscode: hoscode as string,
      depcode: depcode,
      workDate: workDate,
    });
    setDoctors(doctors);
  }

  //左侧树状结构切换选择的回调
  let onSelect = async (selectedKeys: Key[], info: any) => {
    //受控组件
    let { depcode, depname } = info.node;
    //更新状态
    setDepcode(depcode);
    setDepname(depname);
  };

  let switchWorkDate = async (workDate: string) => {
    //更新状态
    setWorkDate(workDate);
  }

  return (
    <Card>
      {/* 路径导航 start */}
      <p>
        选择: {hosname} / {depname} / {workDate}
      </p>
      {/* 路径导航 end */}

      {/* 主题内容部分 start */}
      <Row gutter={20}>
        {/* 左侧部分 */}
        <Col span={5}>
          <div
            style={{
              height: height,
              border: "solid 1px #ccc",
              overflowY: "scroll",
            }}
          >
            <Tree
              fieldNames={{
                key: "depcode",
                title: "depname",
              }}
              onSelect={onSelect}
              selectedKeys={[depcode]}
              expandedKeys={expandedKeys}
              treeData={departments as []}
            />
          </div>
        </Col>

        {/* 右侧部分 */}
        <Col span={19}>
          {/* 排班日期 */}
          <div>
            {schedule.map((item) => {
              return (
                <Tag
                  color={item.workDate === workDate ? "green" : ""}
                  key={item.workDate}
                  onClick={() => {
                    switchWorkDate(item.workDate);
                  }}
                >
                  <div>
                    {item.workDate} {item.dayOfWeek}
                  </div>
                  <div>
                    {item.availableNumber} / {item.reservedNumber}
                  </div>
                </Tag>
              );
            })}
          </div>
          <div className="h-20"></div>

          {/* 分页 */}
          <Pagination
            onChange={(page, pageSize) => {
              //更新状态
              setCurrent(page);
              setPageSize(pageSize);
            }}
            current={current}
            total={total}
            pageSize={pageSize}
          />
          <div className="h-20"></div>

          {/* 表格部分 */}
          <Table
            rowKey={"id"}
            columns={columns}
            dataSource={doctors}
            bordered
            pagination={false}
          ></Table>
          <div className="h-20"></div>
          {/* 返回按钮 */}
          <Button onClick={() => {
            navigate('/syt/hospital/hospitalList');
          }}>返回</Button>
        </Col>
      </Row>
      {/* 主题内容部分 end */}
    </Card>
  );
}
